package org.cy.evolution.ioc.context;

import org.cy.evolution.ioc.factory.EvolutionInjector;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
public final class InjectorContext<T> extends AbstractContext {

    private static final String SUFFIX = "Injector";
    private Map<String, T> injectors = new HashMap<>(0);

    @Override
    public T get(String className) {
        String injectorClassName = className + SUFFIX;
        T injector = injectors.get(injectorClassName);
        if (null == injector) {
            Class<?> builderClass = findBuilderClass(injectorClassName);
            if (null != builderClass) {
                try {
                    EvolutionInjector.Builder builder = (EvolutionInjector.Builder) builderClass.newInstance();
                    injector = (T) builder.create();
                    injectors.put(injectorClassName, injector);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return injector;
    }
}
